import Honey from '../../utils/honey';

const app = getApp();
const honey = new Honey();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const that = this;

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    that.setData({
      phone: wx.getStorageSync('phone'),
      password: wx.getStorageSync('password')
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  inputPhone: function(e) {
    const that = this;
    this.setData({
      phone: e.detail.value
    })
  },
  inputPassword: function(e) {
    const that = this;
    this.setData({
      password: e.detail.value
    })
  },
  toLogin: function() {
    const that = this;

    const phone = that.data.phone;
    const password = that.data.password;
    wx.showLoading({
      title: "加载中"
    });
    honey.post({
      alias: 'login',
      data: {
        user_name: phone,
        password: password
      },
      success: function(res) {
        wx.setStorageSync('phone', phone);
        wx.setStorageSync('password', password);
        wx.setStorageSync('user', res.data.data);
        wx.hideLoading();
        wx.showToast({
          title: '登录成功',
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })},1000)
        
        honey.alert({
          title: '登录成功',
          content: '正在返回上一页',
          success: function(res) {
            let referrer = wx.getStorageSync('referrer');
            wx.removeStorageSync('referrer');
            referrer = referrer ? referrer : {
              tab: true,
              path: '/pages/index/index'
            };
            if (referrer.tab) {
              wx.switchTab({
                url: referrer.path
              })
            } else {
              wx.redirectTo({
                url: referrer.path
              })
            }
          }
        })
      }
    })
  }
})